<template>
  <div class="admin-layout">
    <AdminHeader />
    <div class="main-wrapper">
      <AdminNavbar />
      <div class="content-wrapper">
        <div class="process-task-container">
          <div class="page-header">
            <h2>为生产线创建工序区</h2>
            <div class="header-actions">
              <el-button type="primary" @click="refreshData">
                <el-icon><Refresh /></el-icon> 刷新数据
              </el-button>
            </div>
          </div>

          <div class="main-content">
            <!-- 空闲生产线列表 -->
            <div class="production-line-section">
              <div class="section-header">
                <h3>空闲生产线列表</h3>
                <el-input
                  v-model="lineSearchKeyword"
                  placeholder="搜索生产线ID或产品型号"
                  clearable
                  class="search-input"
                  @clear="handleLineSearch"
                >
                  <template #suffix>
                    <el-icon class="el-input__icon" @click="handleLineSearch">
                      <Search />
                    </el-icon>
                  </template>
                </el-input>
              </div>

              <div class="line-list" v-loading="lineLoading">
                <div
                  v-for="line in filteredLines"
                  :key="line.lineId"
                  class="line-card"
                >
                  <div class="line-header">
                    <span class="line-id">生产线ID: {{ line.lineId }}</span>
                    <el-tag type="info">{{ line.status }}</el-tag>
                  </div>
                  <div class="line-info">
                    <div class="info-item">
                      <span class="label">产品型号:</span>
                      <span class="value">{{ line.productModel }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">创建时间:</span>
                      <span class="value">{{ formatDateTime(line.createdAt) }}</span>
                    </div>
                  </div>
                  <div class="line-actions">
                    <el-button type="primary" size="small" @click="openCreateDialog(line)">
                      创建工序区
                    </el-button>
                  </div>
                </div>

                <div v-if="filteredLines.length === 0 && !lineLoading" class="empty-placeholder">
                  <el-empty description="暂无空闲生产线" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建工序区对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="创建工序区"
      width="500px"
    >
      <el-form :model="processForm" :rules="processRules" ref="processFormRef" label-width="100px">
        <div class="dialog-line-info">
          <p><strong>生产线ID:</strong> {{ selectedLine.lineId }}</p>
          <p><strong>产品型号:</strong> {{ selectedLine.productModel }}</p>
          <p><strong>状态:</strong> {{ selectedLine.status }}</p>
        </div>

        <el-form-item label="工序区名称" prop="processName">
          <el-input v-model="processForm.processName" placeholder="请输入工序区名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createProcessArea">创建</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import AdminHeader from '@/components/AdminHeader.vue'
import AdminNavbar from '@/components/AdminNavbar.vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getFreeProductionLine } from '@/api/production'
import request from '@/utils/request'

// 数据定义
const productionLines = ref([])
const lineLoading = ref(false)
const lineSearchKeyword = ref('')
const createDialogVisible = ref(false)
const selectedLine = ref({})
const processForm = ref({
  processName: ''
})
const processFormRef = ref(null)
const processRules = {
  processName: [
    { required: true, message: '请输入工序区名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 过滤后的生产线列表
const filteredLines = computed(() => {
  if (!lineSearchKeyword.value) return productionLines.value

  const keyword = lineSearchKeyword.value.toLowerCase()
  return productionLines.value.filter(line =>
    line.lineId.toString().includes(keyword) ||
    (line.productModel && line.productModel.toLowerCase().includes(keyword))
  )
})

// 获取空闲生产线列表
const fetchProductionLines = async () => {
  lineLoading.value = true
  try {
    const res = await getFreeProductionLine()
    if (res.success) {
      productionLines.value = res.data || []
    } else {
      ElMessage.error(res.message || '获取空闲生产线列表失败')
    }
  } catch (error) {
    console.error('获取空闲生产线列表失败:', error)
    ElMessage.error('获取空闲生产线列表失败')
  } finally {
    lineLoading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  fetchProductionLines()
}

// 搜索处理
const handleLineSearch = () => {
  // 过滤由计算属性处理
}

// 打开创建工序区对话框
const openCreateDialog = (line) => {
  selectedLine.value = line
  processForm.value.processName = ''
  createDialogVisible.value = true
}

// 创建工序区
const createProcessArea = async () => {
  if (!processFormRef.value) return

  await processFormRef.value.validate(async (valid) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        text: '创建中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      try {
        const res = await request({
          url: '/processLine/createProcessArea',
          method: 'get',
          params: {
            processLineId: selectedLine.value.lineId,
            processName: processForm.value.processName
          }
        })

        if (res.success) {
          ElMessage.success('工序区创建成功')
          createDialogVisible.value = false
          fetchProductionLines() // 刷新生产线列表
        } else {
          ElMessage.error(res.message || '创建工序区失败')
        }
      } catch (error) {
        console.error('创建工序区失败:', error)
        ElMessage.error('创建工序区失败')
      } finally {
        loading.close()
      }
    }
  })
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return new Date(datetime).toLocaleString()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchProductionLines()
})
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7f9;
}

.main-wrapper {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.content-wrapper {
  flex: 1;
  padding: 24px;
  overflow: auto;
  background: #fff;
  margin: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.process-task-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.production-line-section {
  background: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  flex: 1;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.search-input {
  width: 250px;
}

.line-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  max-height: 600px;
  overflow-y: auto;
}

.line-card {
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.line-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.line-id {
  font-weight: bold;
  font-size: 16px;
}

.line-info {
  margin-bottom: 15px;
}

.info-item {
  display: flex;
  margin-bottom: 5px;
}

.label {
  width: 100px;
  color: #606266;
}

.value {
  flex: 1;
  color: #303133;
}

.line-actions {
  display: flex;
  justify-content: flex-end;
}

.empty-placeholder {
  padding: 30px 0;
  text-align: center;
  margin: auto;
}

.dialog-line-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.dialog-line-info p {
  margin: 8px 0;
}
</style>
